package org.example.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.example.domain.SysMenu;
import org.example.model.Result;
import org.example.service.SysMenuService;
import org.example.utils.AuthUtils;
import org.example.vo.MenuAndAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 系统权限控制层
 */
@Api(tags = "系统权限接口管理")
@RequestMapping("/sys/menu")
@RestController
public class SysMenuController {

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private AuthUtils authUtils;

    //  sys/menu/nav
    @ApiOperation("查询用户的菜单权限和操作权限")
    @GetMapping("/nav")
    public Result<MenuAndAuth> loadUserMenuAndAuth() {

        Long loginUserId = authUtils.getLoginUserId();

        // 根据用户标识查询操作权限集合
        Set<String> perms = AuthUtils.getLoginUserPerms();

        // 根据用户标识查询菜单权限集合
        Set<SysMenu> menus = sysMenuService.queryUserMenuListByUserId(loginUserId);

        MenuAndAuth menuAndAuth = new MenuAndAuth(menus, perms);


        return Result.success(menuAndAuth);
    }

    @ApiOperation("查询系统所有权限集合")
    @GetMapping("table")
    @PreAuthorize("hasAuthority('sys:menu:list')")
    public Result<List<SysMenu>> loadAllSysMenuList() {
        List<SysMenu> list =sysMenuService.queryAllSysMenuList();
        return Result.success(list);

    }

    @ApiOperation("新增权限")
    @PostMapping
    @PreAuthorize("hasAuthority('sys:menu:save')")
    public Result<String> saveSysMenu(@RequestBody SysMenu sysMenu) {
        Boolean saved = sysMenuService.saveSysMenu(sysMenu);
        return Result.handle(saved);
    }

    @ApiOperation("根据标识查询菜单权限信息")
    @GetMapping("/info/{menuId}")
    @PreAuthorize("hasAuthority('sys:menu:info')")
    public Result<SysMenu> loadSysMenuInfo(@PathVariable Long menuId) {
        SysMenu sysMenu = sysMenuService.getById( menuId);
        return Result.success(sysMenu);
    }

    @ApiOperation("修改权限信息")
    @PutMapping
    @PreAuthorize("hasAuthority('sys:menu:update')")
    public Result<String> updateSysMenu(@RequestBody SysMenu sysMenu) {
        Boolean updated = sysMenuService.modifySysMenu(sysMenu);
        return Result.handle(updated);
    }

    @ApiOperation("删除权限")
    @DeleteMapping("/{menuId}")
    @PreAuthorize("hasAuthority('sys:menu:delete')")
    public Result<String> deleteSysMenu(@PathVariable Long menuId) {
        Boolean deleted = sysMenuService.removeSysMenuById(menuId);
        return Result.handle(deleted);
    }

}

